"""
Task API Routes for TaskMaster v1
AceFlow v3.0 - Implementation Phase

Provides task CRUD operations with user data isolation
"""

from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime
from ..api.auth import get_current_user
from ..services.task_service import get_task_service

# Create router
router = APIRouter()

# Pydantic models for request/response
class TaskCreateRequest(BaseModel):
    title: str
    description: Optional[str] = None
    due_date: datetime
    priority: int  # 1=High, 2=Medium, 3=Low

class TaskUpdateRequest(BaseModel):
    title: Optional[str] = None
    description: Optional[str] = None
    due_date: Optional[datetime] = None
    priority: Optional[int] = None
    status: Optional[str] = None  # pending, in_progress, completed

class TaskResponse(BaseModel):
    id: int
    user_id: int
    title: str
    description: Optional[str]
    due_date: Optional[str]
    priority: int
    status: str
    created_at: Optional[str]
    notified: bool

class ApiResponse(BaseModel):
    success: bool
    message: str
    task_id: Optional[int] = None


@router.post("/", response_model=ApiResponse)
async def create_task(
    request: TaskCreateRequest,
    user_id: int = Depends(get_current_user)
):
    """
    Create a new task

    This endpoint creates a new task for the authenticated user.
    All tasks are automatically isolated by user_id.
    """
    task_service = get_task_service()
    result = task_service.create_task(
        user_id=user_id,
        title=request.title,
        description=request.description,
        due_date=request.due_date,
        priority=request.priority
    )

    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["message"])

    return ApiResponse(**result)


@router.get("/", response_model=List[TaskResponse])
async def get_user_tasks(
    status: Optional[str] = None,
    user_id: int = Depends(get_current_user)
):
    """
    Get user's tasks

    This endpoint returns all tasks for the authenticated user.
    Supports optional status filtering.
    """
    print(f"DEBUG: get_user_tasks called with user_id={user_id}, status={status}")
    try:
        task_service = get_task_service()
        print(f"DEBUG: task_service obtained: {task_service}")
        tasks = task_service.get_user_tasks(user_id=user_id, status=status)
        print(f"DEBUG: tasks retrieved: {len(tasks) if tasks else 0} tasks")

        result = [TaskResponse(**task) for task in tasks]
        print(f"DEBUG: response prepared with {len(result)} tasks")
        return result
    except Exception as e:
        print(f"ERROR in get_user_tasks: {str(e)}")
        import traceback
        traceback.print_exc()
        raise


@router.get("/{task_id}", response_model=TaskResponse)
async def get_task(
    task_id: int,
    user_id: int = Depends(get_current_user)
):
    """
    Get a specific task

    This endpoint returns a specific task by ID.
    User can only access their own tasks (data isolation).
    """
    task_service = get_task_service()
    task = task_service.get_task_by_id(task_id=task_id, user_id=user_id)

    if not task:
        raise HTTPException(status_code=404, detail="Task not found or access denied")

    return TaskResponse(**task)


@router.put("/{task_id}", response_model=ApiResponse)
async def update_task(
    task_id: int,
    request: TaskUpdateRequest,
    user_id: int = Depends(get_current_user)
):
    """
    Update a task

    This endpoint updates an existing task.
    User can only update their own tasks (data isolation).
    """
    task_service = get_task_service()
    result = task_service.update_task(
        task_id=task_id,
        user_id=user_id,
        title=request.title,
        description=request.description,
        due_date=request.due_date,
        priority=request.priority,
        status=request.status
    )

    if not result["success"]:
        if "不存在" in result["message"]:
            raise HTTPException(status_code=404, detail=result["message"])
        else:
            raise HTTPException(status_code=400, detail=result["message"])

    return ApiResponse(success=True, message=result["message"])


@router.delete("/{task_id}", response_model=ApiResponse)
async def delete_task(
    task_id: int,
    user_id: int = Depends(get_current_user)
):
    """
    Delete a task

    This endpoint deletes an existing task.
    User can only delete their own tasks (data isolation).
    """
    task_service = get_task_service()
    result = task_service.delete_task(task_id=task_id, user_id=user_id)

    if not result["success"]:
        if "不存在" in result["message"]:
            raise HTTPException(status_code=404, detail=result["message"])
        else:
            raise HTTPException(status_code=400, detail=result["message"])

    return ApiResponse(success=True, message=result["message"])
